//思路：练习链表

import java.util.List;

public class Solution {

}

class MyLinkedList {
    int size;
    ListNode head;

    public MyLinkedList() {
        size = 0;
        head = new ListNode(0);

    }

    public int get(int index) {
        if (index < 0 || index >= size) {
            return -1;
        }
        ListNode p=head;
        for(int i=0;i<=index;i++){
            p=p.next;
        }
        return p.val;
    }

    public void addAtHead(int val) {
        addAtIndex(0,val);
    }

    public void addAtTail(int val) {
        addAtIndex(size,val);
    }

    public void addAtIndex(int index, int val) {
        if(index>size){
            return;
        }
        ListNode p=new ListNode(val);
        if(index==0){
            p.next=head.next;
            head.next=p;
        } else if (index==size) {
            ListNode k=head;
            while(k.next!=null){
                k=k.next;
            }
            k.next=p;
        }
        else{
            ListNode k=head;
            while(k.next!=null&&index>0){
                k=k.next;
                index--;
            }
            p.next=k.next;
            k.next=p;
        }
        size++;

    }

    public void deleteAtIndex(int index) {
        if(index<0||index>=size){
            return;
        }
        ListNode pre=head;
        for(int i=0;i<index;i++){
            pre=pre.next;
        }
        pre.next=pre.next.next;
        size--;

    }
}
class  ListNode{
    int val;
    ListNode next;

    public ListNode(int val) {
        this.val = val;
    }
}






